package com.example.content_android.ui.downloads;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.content_android.R;
import com.example.content_android.ui.home.ArticleListFragment;
import com.nostra13.universalimageloader.utils.L;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.DOWNLOAD_SERVICE;

public class DownloadsFragment extends Fragment implements AdapterView.OnItemClickListener {
    private ImageView ivDeleteText;
    private EditText etSearch;
    private DownloadsViewModel downloadsViewModel;
    ListView listView;
    SimpleAdapter simpleAdapter;
    private ArticleListFragment.OnFragmentInteractionListener mListener;
    List<String> fileList = new ArrayList<>();
    public List<Map<String, Object>> list = new ArrayList<>();
    private String keywords="";

    @Override
    @SuppressLint("NewApi")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        try {
            list.clear();
            initData(keywords);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
//        downloadsViewModel =
//                ViewModelProviders.of(this).get(DownloadsViewModel.class);
        View root = inflater.inflate(R.layout.fragment_downloads, container, false);
//        final TextView textView = root.findViewById(R.id.text_downloads);
//        downloadsViewModel.getText().observe(this, new Observer<String>() {
//            @Override
//            public void onChanged(@Nullable String s) {
//                textView.setText(s);
//            }
//        });
        listView = root.findViewById(R.id.downloads_view);


        simpleAdapter = new SimpleAdapter(getActivity(), getData(), R.layout.download_item, new String[]{"filename"}, new int[]{R.id.file_name});
        listView.setAdapter(simpleAdapter);

        listView.setOnItemClickListener(this);
        ivDeleteText = root.findViewById(R.id.ivDeleteText);
        etSearch = root.findViewById(R.id.etSearch);

        Button searchButton = root.findViewById(R.id.btnSearch);
        // 监听点击事件
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               String keywords=etSearch.getText().toString();
                try {
                    list.clear();
                    initData(keywords);

                    simpleAdapter = new SimpleAdapter(getActivity(), getData(), R.layout.download_item, new String[]{"filename"}, new int[]{R.id.file_name});
                    listView.setAdapter(simpleAdapter);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        ivDeleteText.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                etSearch.setText("");
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {

            public void onTextChanged(CharSequence s, int start, int before, int count) {
               System.out.println(s);

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ivDeleteText.setVisibility(View.GONE);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                }
            }
        });


        return root;
    }

    private List<Map<String, Object>> getData() {

        return list;
    }


    private void initData(String keywords) throws IOException {
        Response response = OkHttpUtils
                .get()//
                .url("https://www.turkeylike.cn:8900/fzulab/download/list")//
                .addParams("limit", "100")
                .addParams("keywords", keywords)
                .tag(this)//
                .build()//
                .execute();

        JSONObject jsonObject = JSONObject.parseObject(response.body().string());

        if (jsonObject.getInteger("code") == 500) {
            String msg = jsonObject.getString("msg");

            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
            return;

        }
        if (jsonObject.getInteger("code") == 0) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray fileArray = result.getJSONArray("list");


            if (fileArray != null && fileArray.size() > 0) {
                for (int i = 0; i < fileArray.size(); i++) {
                    JSONObject str = JSON.parseObject(fileArray.get(i).toString());

                    Map map = new HashMap();
                    map.put("filename", str.get("filename").toString());
                    map.put("fileurl", str.get("fileurl").toString());
                    list.add(map);
                }
            }

        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        L.i("position:" + position);
        Map map = (HashMap<String, String>) listView.getAdapter().getItem(position);
        String filename = (String) map.get("filename");
        String fileurl = (String) map.get("fileurl");

//        String text = listView.getAdapter().getItem(position).toString();
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl));
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle("下载");
        request.setDescription(filename);
        request.setVisibleInDownloadsUi(true);
        request.allowScanningByMediaScanner();

        //设置下载路径 sdcard/download/
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "content");

        //设置下载的路径
        File file = new File(this.getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename);
        request.setDestinationUri(Uri.fromFile(file));
        file.getAbsolutePath();
        //获取DownloadManager
        DownloadManager downloadManager = (DownloadManager) this.getContext().getSystemService(DOWNLOAD_SERVICE);
        //将下载请求放入队列
        long requestId = downloadManager.enqueue(request);

        //使用DownloadManager.Query可以查询下载状态
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(requestId);
        try {
            boolean flag = true;
            while(flag) {
                Cursor cursor = downloadManager.query(query);
                if (cursor != null && cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)); //获取下载状态
                    String path = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); //获取保存路径
                    switch(status){
                        //判断下载状态
                        case DownloadManager.STATUS_SUCCESSFUL:
                            flag = false;
                            Log.d("Jason", "download success");
                            break;
                        case DownloadManager.STATUS_FAILED:
                            flag = false;
                            Log.d("Jason", "download fail");
                            break;
                    }
                }

                if(cursor != null) {
                    cursor.close();
                }
            }
        }catch(Exception e) {
            e.printStackTrace();
        }


        L.i("position:" + position + "text" + filename);
    }


//    //download the new app
//    private void downLoadNewApp(String fileUrl, String fileName) {
//
//        if (StringUtils.isEmpty(fileUrl)) {
//
//            Toast.makeText(getActivity(), "文件URL为空！", Toast.LENGTH_SHORT);
//
//
//            return;
//        }
//
//        final ProgressDialog dialog = new ProgressDialog(getActivity());
//        dialog.setTitle("正在下载");
//        dialog.setMessage(fileName);
//        dialog.setCancelable(false);
//        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        dialog.show();
//
////        if (!NetUtils.hasNet(SplashActivity.this)) {
////            ToastUtils.showToast("请检查网络环境");
////            return;
////        }
//
//        System.out.println("SplashActivity.downLoadNewApp=" + fileUrl);
//
//        OkHttpUtils
//                .get()
//                .url(fileUrl)
//                .build()
//                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), Conts.NEW_APP_NAME) {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//
//                        System.out.println("SplashActivity.onError=哈哈哈");
////                        ToastUtils.showToast("下载更新包失败");
//                    }
//
//                    @Override
//                    public void inProgress(float progress, long total, int id) {
//                        super.inProgress(progress, total, id);
//                        dialog.setProgress((int) (100 * progress));
//                    }
//
//                    @Override
//                    public void onResponse(File response, int id) {
//
//                        Intent intent = new Intent();
//                        intent.setAction(Intent.ACTION_VIEW);
//                        intent.addCategory(Intent.CATEGORY_DEFAULT);
//                        intent.setDataAndType(Uri.fromFile(response),
//                                "application/vnd.android.package-archive");
//                        startActivityForResult(intent, 0);
//                    }
//                });
//    }

}